package com.homeinns.lyx.server.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.homeinns.common.ProductInfoOutput;
import com.homeinns.lyx.server.utils.JsonUtil;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ProductInfoOutputReceive {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("lyx-productInfo"))
    public void process(String message){

        System.out.println("----------------" + message);
        List<ProductInfoOutput> productInfoOutputs= (List<ProductInfoOutput>) JsonUtil.fromJson(message,new TypeReference<List<ProductInfoOutput>>(){});

        productInfoOutputs.forEach(x ->
            redisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, x.getProductId()),
                    String.valueOf(x.getProductStock())));
    }
}
